using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using PetShop.Domain.Model;
using PetShop.Infrastructure.NHibernate;
using NHibernate;


namespace PetShop.Infrastructure.Gateways
{

	public class ProductGateway {

     

        private readonly ISession _session;

        public ProductGateway()
        {
            _session = NHibernateHttpModule.CurrentSession;
        }
    

        public IList GetProductsByCategory(string category)
        {

            IList productsByCategory = new ArrayList();
            IQuery query = _session.CreateQuery("SELECT p FROM ProductEntity as p WHERE p.Category = :Category");
            query.SetString("Category", category);
            productsByCategory = query.List();
            return productsByCategory;
        }

        public IList GetProductsBySearch(string[] keywords)
        {

            IList productsBySearch = new ArrayList();

            int numKeywords = keywords.Length;

            StringBuilder hql = new StringBuilder("SELECT p FROM ProductEntity as p WHERE ((");

            for (int i = 0; i < numKeywords; i++)
            {
                hql.Append(string.Format("LOWER(p.Name) LIKE {0}  OR LOWER(Category) LIKE {0} ", ":Keyword" + i.ToString()));
                hql.Append(i + 1 < numKeywords ? ") OR (" : "))");
            }

            string sqlProductsBySearch = hql.ToString();


            IQuery query = _session.CreateQuery(sqlProductsBySearch);

            for (int i = 0; i < numKeywords; i++)
            {
                string name = "Keyword" + i.ToString();
                string value = "%" + keywords[i] + "%";
                query.SetString(name, value);
            }

            productsBySearch = query.List();

            return productsBySearch;

		}
	}
}
